// 视频播放器管理
class VideoPlayer {
    constructor() {
        // 获取视频ID
        const pathParts = window.location.pathname.split('/');
        this.videoId = pathParts[pathParts.length - 1];
        console.log('视频ID:', this.videoId);
        
        // 获取DOM元素
        this.videoPlayer = document.getElementById('videoPlayer');
        this.videoTitle = document.getElementById('videoTitle');
        this.videoDescription = document.getElementById('videoDescription');
        this.viewCount = document.getElementById('viewCount');
        this.likeCount = document.getElementById('likeCount');
        this.commentCount = document.getElementById('commentCount');
        this.authorAvatar = document.getElementById('authorAvatar');
        this.authorName = document.getElementById('authorName');
        this.commentInput = document.getElementById('commentInput');
        this.submitComment = document.getElementById('submitComment');
        this.commentsList = document.getElementById('commentsList');

        // 检查必要的DOM元素是否存在
        const requiredElements = {
            videoPlayer: this.videoPlayer,
            videoTitle: this.videoTitle,
            videoDescription: this.videoDescription,
            viewCount: this.viewCount,
            likeCount: this.likeCount,
            commentCount: this.commentCount,
            authorAvatar: this.authorAvatar,
            authorName: this.authorName,
            commentInput: this.commentInput,
            submitComment: this.submitComment,
            commentsList: this.commentsList
        };

        for (const [name, element] of Object.entries(requiredElements)) {
            if (!element) {
                console.error(`找不到必要的DOM元素: ${name}`);
            }
        }

        // 初始化
        this.init();
    }

    async init() {
        try {
            console.log('开始初始化视频播放器...');
            
            // 检查视频ID
            if (!this.videoId) {
                throw new Error('无法获取视频ID');
            }
            
            // 加载视频信息
            await this.loadVideoInfo();
            
            // 加载评论
            await this.loadComments();
            
            // 设置评论提交事件
            if (this.submitComment) {
                this.submitComment.addEventListener('click', () => this.submitCommentHandler());
            }
            
            // 更新观看次数
            await this.updateViewCount();
            
            console.log('视频播放器初始化完成');
        } catch (error) {
            console.error('初始化失败:', error);
            alert('加载视频失败，请刷新页面重试');
        }
    }

    async loadVideoInfo() {
        try {
            console.log('正在加载视频信息...');
            const response = await fetch(`/api/videos/${this.videoId}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const video = await response.json();
            console.log('获取到的视频信息:', video);
            
            // 更新视频信息
            if (!video.url) {
                throw new Error('视频URL不存在');
            }
            
            // 设置视频源
            if (this.videoPlayer) {
                // 确保视频URL是完整的
                const videoUrl = video.url.startsWith('http') ? video.url : `${window.location.origin}${video.url}`;
                console.log('设置视频源:', videoUrl);
                this.videoPlayer.src = videoUrl;
                
                // 添加视频加载事件监听
                this.videoPlayer.addEventListener('loadeddata', () => {
                    console.log('视频数据加载完成');
                });
                
                this.videoPlayer.addEventListener('error', (e) => {
                    console.error('视频加载错误:', e);
                    console.error('错误详情:', this.videoPlayer.error);
                });
            }
            
            // 更新视频信息
            if (this.videoTitle) this.videoTitle.textContent = video.title;
            if (this.videoDescription) this.videoDescription.textContent = video.description;
            if (this.viewCount) this.viewCount.textContent = video.views;
            if (this.likeCount) this.likeCount.textContent = video.likes;
            if (this.commentCount) this.commentCount.textContent = video.comments;
            
            // 更新作者信息
            if (video.author) {
                if (this.authorAvatar) this.authorAvatar.src = video.author.avatar || '/images/default-avatar.png';
                if (this.authorName) this.authorName.textContent = video.author.nickname;
            }
        } catch (error) {
            console.error('加载视频信息失败:', error);
            const errorMessage = `加载视频失败: ${error.message}`;
            console.error(errorMessage);
            alert(errorMessage);
        }
    }

    async loadComments() {
        try {
            console.log('正在加载评论...');
            const response = await fetch(`/api/videos/${this.videoId}/comments`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const comments = await response.json();
            console.log('获取到的评论:', comments);
            
            // 清空现有评论
            if (this.commentsList) {
                this.commentsList.innerHTML = '';
                
                // 添加新评论
                comments.forEach(comment => {
                    const commentElement = this.createCommentElement(comment);
                    this.commentsList.appendChild(commentElement);
                });
            }
        } catch (error) {
            console.error('加载评论失败:', error);
            if (this.commentsList) {
                this.commentsList.innerHTML = '<div class="error-message">加载评论失败，请刷新页面重试</div>';
            }
        }
    }

    createCommentElement(comment) {
        const commentDiv = document.createElement('div');
        commentDiv.className = 'comment-item';
        
        const timestamp = new Date(comment.timestamp).toLocaleString();
        
        commentDiv.innerHTML = `
            <div class="comment-content">
                <div class="comment-header">
                    <img src="${comment.author?.avatar || '/images/default-avatar.png'}" alt="${comment.author?.nickname || '用户'}">
                    <span class="comment-author">${comment.author?.nickname || '匿名用户'}</span>
                    <span class="comment-time">${timestamp}</span>
                </div>
                <div class="comment-text">${comment.content}</div>
            </div>
        `;
        
        return commentDiv;
    }

    async submitCommentHandler() {
        if (!this.commentInput || !this.submitComment) {
            console.error('评论相关元素不存在');
            return;
        }

        const content = this.commentInput.value.trim();
        if (!content) {
            alert('请输入评论内容');
            return;
        }

        try {
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                return;
            }

            console.log('正在提交评论...');
            const response = await fetch(`/api/videos/${this.videoId}/comments`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ content })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || '发表评论失败');
            }

            const newComment = await response.json();
            console.log('评论提交成功:', newComment);
            
            // 添加新评论到列表顶部
            if (this.commentsList) {
                const commentElement = this.createCommentElement(newComment);
                this.commentsList.insertBefore(commentElement, this.commentsList.firstChild);
            }
            
            // 清空输入框并更新评论数
            if (this.commentInput) this.commentInput.value = '';
            if (this.commentCount) {
                const currentCount = parseInt(this.commentCount.textContent) || 0;
                this.commentCount.textContent = currentCount + 1;
            }
        } catch (error) {
            console.error('发表评论失败:', error);
            alert(error.message || '发表评论失败，请重试');
        }
    }

    async updateViewCount() {
        try {
            console.log('正在更新观看次数...');
            const response = await fetch(`/api/videos/${this.videoId}/view`, {
                method: 'POST'
            });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            console.log('观看次数更新成功:', data);
            if (this.viewCount) this.viewCount.textContent = data.views;
        } catch (error) {
            console.error('更新观看次数失败:', error);
        }
    }
}

// 初始化视频播放器
document.addEventListener('DOMContentLoaded', () => {
    // 只有在视频页面才初始化视频播放器
    const videoPlayer = document.getElementById('videoPlayer');
    if (videoPlayer) {
        const player = new VideoPlayer();
    }
}); 